<?php
namespace app\admin\controller;
use think\Request;

use app\admin\model\TradeBill;
use app\admin\model\Check;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UploadImgException;
use app\lib\exception\ErrorException;
use think\Exception;
use think\Db;
use app\admin\model\Trade as TradeModel;
class Trade extends Base{

    //流水汇总
    public function index() 
    {
        $data = [];
        $data['agent_name'] = input('agent');
        $agent_id = input('id');
        $level = input('level');
        $feelist = $this->getFeeByAgent($agent_id);//代理商分润
        if($data['agent_name']){
            $agentlist = getNextAgent($agent_id,$level);
            
            if($agentlist && array_key_exists('children',$agentlist))
            {
                foreach($agentlist['children'] as $k=>$v)
                {
                   
                    $agentlist['children'][$k]['fee'] = self::getFeeByAgent($v['chnlId']);
                    
                    $agentlist['children'][$k]['fee']['payfee_differ_num'] = ($feelist['payfee_num']-$agentlist['children'][$k]['fee']['payfee_num'])>0 ?($feelist['payfee_num']-$agentlist['children'][$k]['fee']['payfee_num']): 0.00005*100;//还款费率差
                    $agentlist['children'][$k]['fee']['getfee_differ_num'] = ($feelist['getfee_num']-$agentlist['children'][$k]['fee']['getfee_num'])>0 ?($feelist['getfee_num']-$agentlist['children'][$k]['fee']['getfee_num']): 0.00005*100;//还款费率差
                  
                    $agentlist['children'][$k]['fee']['payfee_differ'] = ($agentlist['children'][$k]['fee']['payfee_differ_num']).'%';
                    $agentlist['children'][$k]['fee']['getfee_differ'] = ($agentlist['children'][$k]['fee']['getfee_differ_num']).'%';
                    //$agent_name = '['.$agentlist['children'][$k]['chnlId'].']'.$agentlist['children'][$k]['chnlName'];
                    $agentlist['children'][$k]['file'] = TradeModel::getTradeBillSum($agentlist['children'][$k]['chnlName'],0,$agentlist['children'][$k]['chnlId'],$level+1);//未结算
                    $agentlist['children'][$k]['settle_file'] = TradeModel::getTradeBillSum($agentlist['children'][$k]['chnlName'],1,$agentlist['children'][$k]['chnlId'],$level+1);//已结算
                }
            }else{
                 throw new UploadImgException([
                    'msg' =>'该代理商没有下级代理'
                    ]);
            }
            
        }
       
        $agentlist = array_merge($feelist,$agentlist);
        
        $this->assign('data',$agentlist);
        return view();
    }
   
    //获取费率
    static function getFeeByAgent($agent_id='')
    {
        $feeList = getFee($agent_id);
        foreach($feeList as $v){
            if($v['gateId'] == 'helipayapj'){//还款
                $payfee = substr($v['t0Fee'],4,6);
            }elseif($v['gateId'] == 'eposys'){//收款
                $getfee = substr($v['t0Fee'],4,6);
            }
        }
        $data['payfee_num'] = (0.0085-$payfee+0.0005)*100;
        $data['getfee_num'] = (0.0060-$getfee+0.0005)*100;
        $data['payfee'] = sprintf("%.2f",$data['payfee_num']).'%';//还款费率
        $data['getfee'] = sprintf("%.2f",$data['getfee_num']).'%';//收款费率
        return $data;
    }
    
    //流水明细
    public function show($id)
    {
        $agent_id = input('agent_id');
        $trade_id = input('id');
        $agentName = input('agent');
        $agentName = '['.$agent_id.']'.$agentName;
        if($trade_id > 0){
             $list = Db::name('trade_bill')->where('trade_id',$trade_id)->where("trade_status",'交易成功')
             ->where('agent_name',$agentName)->paginate(10);
        }else{
             $list = Db::name('trade_bill')->paginate(10);
        }
        
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        return view();
    }
    //结算页面
    public function statement()
    {   
         $data['trade_id'] = input('id');
         $data['agent_id'] = input('agent_id');
         $data['parentagent_id'] = input('parentagent_id');
         //$agentfee = self::getFeeByAgent($data['agent_id']);
         //$parentfee = self::getFeeByAgent($data['parentagent_id']);
         $data['agent'] = getAgentDetail($data['agent_id'])['chnlName'];
         $data['parentagent'] = getAgentDetail($data['parentagent_id'])['chnlName'];
         //$data['getfee_differ'] = ($parentfee['getfee'] - $agentfee['getfee'])/100;//收款费率差
         //$data['payfee_differ'] = ($parentfee['payfee'] - $agentfee['payfee'])/100;//还款费率差
	    $data['getfee_differ'] = input('getfee_differ')/100;//收款费率差
         $data['payfee_differ'] = input('payfee_differ')/100;//还款费率差
         $data['agentName'] = '['.$data['agent_id'].']'.$data['agent'];
       
         $pay_sum = db('trade_bill')->where("trade_id",$data['trade_id'])->where("trade_status",'交易成功')->where('agent_name',$data['agentName'])->where('fee','>',0)
         ->where("pay_gateway",'银联养卡（至平台）')->field("DATE_FORMAT(trade_date,'%Y-%m-%d') as time,sum(trade_money) as pay_sum" )->group('time')->select()->toArray();
         $get_sum = db('trade_bill')->where("trade_id",$data['trade_id'])->where("trade_status",'交易成功')->where('agent_name',$data['agentName'])->where('fee','>',0)
         ->where("pay_gateway",'<>','银联养卡（至平台）')->field("DATE_FORMAT(trade_date,'%Y-%m-%d') as time,sum(trade_money) as get_sum" )->group('time')->select()->toArray();  
            
           $list = array_map(function($Data,$arr){
            return [ 
                'get_sum' => $arr['get_sum'],
                'pay_sum' => $Data['pay_sum'],
                'time' => $arr['time']?? $Data['time'],
                'sum' => ($Data['pay_sum'] + $arr['get_sum']),
            ];
        }, $pay_sum,$get_sum);
         
         foreach($list as $k=>$v){
            $list[$k]['get_sum'] =   sprintf("%.2f",($list[$k]['get_sum']*$data['getfee_differ']));
            $list[$k]['pay_sum'] = sprintf("%.2f",($list[$k]['pay_sum']*$data['payfee_differ']));
            $list[$k]['sum'] = $list[$k]['get_sum'] + $list[$k]['pay_sum'];
         }
        
         $data['time'] = TradeModel::get($data['trade_id'])['time'];
         $data['sum'] = array_sum(array_column($list, 'sum')); 
         $data['get_sum'] = array_sum(array_column($list, 'get_sum')); 
         $data['pay_sum'] = array_sum(array_column($list, 'pay_sum')); 
         
         $this->assign('list', $list);
         $this->assign('data', $data);
         return view();
    }
    //结算行为
    public function settle()
    {
        $trade_id = input('id');
        $agentName = input('agent');;
        $list = db('trade_bill')->where("trade_id",$trade_id)->where("trade_status",'交易成功')->where("status",1)
        ->where('agent_name',$agentName)->select()->toArray();
        
        if(!empty($list)){
            throw new ErrorException([
                'msg' => '已经结算过了',
            ]);
        }else{
            db('trade_bill')->where("trade_id",$trade_id)->where("trade_status",'交易成功')->where('agent_name',$agentName)
            ->update(['status' => 1]);;
        }
         throw new SuccessMessage([
                'msg' => '结算成功',
                
            ]);
        
    }
    //添加到数据库
    public function addTradeBill()
    {
        $file   = request()->file('file');
        $filename = $file->getInfo('name');
        $this->checkIsUpload($filename);
        $info   = $file->validate(['ext'=>'xlsx,xls'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            $dir        =   ROOT_PATH .'/public/uploads/'.$info->getSaveName();
            $retData    = importExcel($dir);//导入excel
            $time =  substr(strstr($filename,'20'),0,23);
            $tradeList    = ['old_file' => $filename,'admin_id'=>session('admin_id'),'new_file'=>$info->getSaveName(),'time'=>$time];
            Db::startTrans();
            try {
                $tradeObj     = TradeModel::create($tradeList);//记录到交易表 
                $tradeData  = self::makeTradeArr($retData,$tradeObj->id);//excel转成数组 
                if(count($tradeData)>2000){//大于两千条记录
                    self::insertAll($tradeData);
                }else{
                    db('trade_bill')->insertAll($tradeData); //0.981315s
                }
                Db::commit();  
            } catch (Exception $ex) {
                Db::rollback();
                throw $ex;
            }
            
            throw new SuccessMessage([
                'msg' => '上传成功',
                'data'=>$dir,
            ]);
        } else {
            // 上传失败获取错误信息
            throw new UploadImgException([
               'msg' =>$file->getError()
            ]);
        }
    
    }
    static function insertAll($tradeData=[])
    {
        $length = intval(count($tradeData)/2000);
        for($i=0;$i<=$length;$i++){
            $tradeNewData = array_slice($tradeData,($i)*2000,2000);
            db('trade_bill')->insertAll($tradeNewData);
        }
        return true;
    }

    static function makeTradeArr($retData=[],$trade_id=0)
    {
        unset($retData[1]);
        $retData = array_merge($retData);

        $func = function($Data) {
                return array(
                    'mer_id' => $Data['B'],
                    'mer_name' => $Data['C'],
                    'mobile' => $Data['D'],
                    'agent_name' => $Data['E'],
                    'order_no' => $Data['F'],
                    'trade_status' => $Data['G'],
                    'trade_money' => $Data['H'],
                    'fee' => $Data['I'],
                    'formula' => $Data['J'],
                    'profit' => $Data['K'],
                    'gateway_cost' => $Data['L'],
                    'return' => $Data['M'],
                    'gain' => $Data['N'],
                    'pay_gateway' => $Data['O'],
                    'trade_date' => $Data['P'],
                    'trade_bank' => $Data['Q'],
                    'trade_card' => $Data['R'],
                    'settle_type' => $Data['S'],
                    'app' => $Data['T'],
                    'cashier' => $Data['U'],
                    'area' => $Data['V'],
                    'order_describe' => $Data['W'],
                    'fail_reason' => $Data['X'],
                );
            };
            $retData = array_map($func, $retData);
           
            foreach($retData as $k=>$v){
                $retData[$k]['trade_id'] = $trade_id;
            }
        return $retData;
    }
    //检测是否上传
    private function checkIsUpload($filename='')
    {
        $file = TradeModel::where("old_file",$filename)->find();
        if($file){
             throw new UploadImgException([
               'msg' =>'文件已上传过'
            ]);
        }
        return true;
    }
  
}